package com.zqwh.xtool.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.zqwh.xtool.ToolsApp;
import com.zqwh.xtool.domain.Msg;
import com.zqwh.xtool.domain.MsgType;
import com.zqwh.yj.sdk.obj.RxMsg;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.RxBus;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;

import java.util.Timer;
import java.util.TimerTask;

import rx.functions.Action1;

import static com.zqwh.xtool.ToolsApp.gHeartbeatModel;

public class HeartbeatService extends Service {
    private static final int NOTIFICATION_ID_CHECK = 100;

    private Timer heartbeatTimer = new Timer(true);
    private boolean online = true;

    @Override
    public void onCreate() {
        super.onCreate();
        startHeartbeatTimer();
        initEventListener();
    }

    private Handler heartbeatHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            heartbeat();
            return false;
        }
    });

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void startHeartbeatTimer() {
        LogUtils.logout("Start to heartbeat");
        heartbeatTimer.schedule(new TimerTask() {
            public void run() {
                if (ToolsApp.getDevId() > 0){
                    heartbeatHandler.sendEmptyMessage(1);
                }
            }
        }, 3 * 1000 , 30*1000);
    }

    private void heartbeat(){
        gHeartbeatModel.heartbeat(ToolsApp.getDevId(), new NetCallback<Msg>() {
            @Override
            public void onSuccess(Msg msg) {
                if (!online){
                    LogUtils.logout("Device set to online");
                    RxBus.getInstance().post(new RxMsg<>(MsgType.MSG_ONLINE, null));
                }
                online = true;
            }

            @Override
            public void onError(String msg) {
                if (online){
                    LogUtils.logout("Device set to offline");
                    RxBus.getInstance().post(new RxMsg<>(MsgType.MSG_OFFLINE, null));
                }
                online = false;
            }
        });
    }

    private void initEventListener() {
        RxBus.getInstance().addSubscription(this, RxBus.getInstance().doSubscribe(RxMsg.class, new Action1<RxMsg>() {
            @Override
            public void call(RxMsg innerMsg) {
                if (innerMsg.getMsgType().equals(MsgType.MSG_NETWORK_CHANGED)) {
                    heartbeatHandler.sendEmptyMessage(1);
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                LogUtils.error("Rxbus fail : " + throwable.getMessage());
                initEventListener();
            }
        }));
    }
}
